import json
import os
import logging
import datetime
# "info":{"funcode":"DMFV4C2001","datatime":"20211119000008387","merid":"lexin","scoreLabels":"YV4E1000_lexin"}
# "data":{"identityNo":"eaaddefc4454e1fca**********************4bbb59a12f203cf9be71c9f","m_loan_defaults_v3":"304.252411","mobileid":"586ea33c152f30f6f**********************c8804d258da88b509aeab07","name":"d0966e64c183bf3f5**********************5af80b689cd311097cd8a26","YV4E1000_lexin":"421"}
import time

from APP.Kafka.constant import *

def loopReceiveData(consumer):
    global isLoopReceiveData
    isLoopReceiveData = True
    for message in consumer:
        kafka_data_dict = json.loads(s=message.value)
        logging.info(kafka_data_dict)
        data_dict = kafka_data_dict[kafkaDataKey]  # 日志中data部分的内容
        info_dict = kafka_data_dict[kafkaInfoKey]  # 日志中info部分的内容
        scoreLabels = info_dict[kafkaScoreLabelsKey]  # 日志info里scorelabels
        labelIdArr = scoreLabels.split(",")
        for labelId in labelIdArr:
            scoreId = labelId
            scoreValue = data_dict[labelId]
            key = data_dict[kafkaNameKey] + ',' + data_dict[kafkaMobileidKey] + ',' + data_dict[kafkaIdentityNoKey]
            dateTime = info_dict[kafkadatatimeKey][0:14]
            needLabels_dict = data_dict
            otherInfo = {merid: info_dict[kafkaMeridKey], funcode: info_dict[kafkaFuncodeKey], kafkaScoreLabelsKey:scoreLabels}
            writeKafkaLog(getScoreBeanStr(scoreId, scoreValue, key, dateTime, needLabels_dict, otherInfo))
        # logging.info("已存储1条数据" + str(datetime.datetime.now()))

def writeKafkaLog(KafkaLogStr):
    from APP.Kafka import kafkaDir
    kafkaScoreDataFileName = 'kafkaScoreData'
    nowData = time.strftime("%Y%m%d", time.localtime())
    logUrl = kafkaDir+kafkaScoreDataFileName+"."+nowData+".log"
    if os.path.exists(logUrl):
        f=open(logUrl, "a")
        f.write(KafkaLogStr+"\n")
        f.close()
    else:
        logging.info("新生成日志文件"+kafkaScoreDataFileName+"."+nowData+".log")
        f = open(logUrl, "x")
        f.write(KafkaLogStr+"\n")
        f.close()

def getScoreBeanStr(scoreId, scoreValue, key, dateTime, needLabels_dict, otherInfo):
    import json
    return scoreId + '|' + str(scoreValue) + '|' + key + '|' + dateTime + '|' + str(
        json.dumps(needLabels_dict)) + '|' + str(json.dumps(otherInfo))